#include<iostream>
#include<string>
#include <cstring>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
void Usage(std::string a)
{
    std::cout<<"Usage:\n\t"<<a<<"ip address"<<" "<<"local port"<<std::endl;
}
int main(int argc,char *argv[])
{
    if(argc != 3)//./client ip地址 端口号
    {
        Usage(argv[0]);
        exit(1);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    int sockfd = socket(AF_INET,SOCK_DGRAM,0);
    if(sockfd < 0)
    {
        std::cerr<<"sock error"<<std::endl;
        exit(2);
    }

    //填充struct sockaddr in(构建目标主机的socket信息)
    struct sockaddr_in server;
    memset(&server,0,sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr=inet_addr(serverip.c_str());
    //client不要显式的bind;Udpclient首次发送数据时OS会自己自动随机的给client绑定
    //为什么？防止端口冲突
    std::string message;
    while (1)
    {
        std::cout<<"请输入#";
        std::getline(std::cin,message);
        sendto(sockfd,message.c_str(),message.size(),0,(struct sockaddr *)&server,sizeof(server));

        char buffer[1024];
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        ssize_t n = recvfrom(sockfd,buffer,sizeof(buffer)-1,0,(struct sockaddr*)&peer,&len);
        if(n > 0)
        {
            buffer[n]=0;
            std::cout<<"服务端返回#"<<buffer<<std::endl;
        }

    }
    
    return 0;
}